package com.google.jguery.client.common;

import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;

public class TermPostings {

	Map<Integer, ArrayList<Integer>> postings;
	int docCount = 0;  //total matched document counts
	int termCount = 0; //Equivalent to term frequency
	
	public TermPostings(HashMap<Integer, ArrayList<Integer>> postings) {
		this.postings = postings;
		docCount = postings.size();
		termCount = 0;
		Set<Integer> docs = postings.keySet();
		for (int doc : docs) {
			termCount += postings.get(doc).size();
		}
	}

	public TermPostings() {
		postings = new HashMap<Integer, ArrayList<Integer>>();
	}
	
	public Set<Integer> getDocIds() {
		return postings.keySet();
	}

	public int getDocCount() {
		return docCount;
	}

	public void setDocCount(int docCount) {
		this.docCount = docCount;
	}

	public int getTermCount() {
		return termCount;
	}

	public void setTermCount(int termCount) {
		this.termCount = termCount;
	}

	public boolean contains(int docId) {
		return postings.containsKey(docId);		
	}
	
	public ArrayList<Integer> getTermsForDocId(int docId) {
		return postings.get(docId);
	}

	private void setTermsForDocId(int docId, ArrayList<Integer> termPos) {
		postings.put(docId, termPos);
	}
	
	public void add(int docId, int pos) {
		if (contains(docId)) {
			getTermsForDocId(docId).add(pos);
			termCount++;
		} else {
			ArrayList<Integer> termPos = new ArrayList<Integer>();
			termPos.add(pos);
			setTermsForDocId(docId, termPos);
			termCount++;
			docCount++;
		}
	}
	
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("DocCount:" + docCount);
		sb.append("TermCount" + termCount);
		if (postings == null || postings.size()==0) {
			sb.append("[]");
		}else {
			sb.append("[");
			for (int k : postings.keySet()) {
				sb.append(k + ":");
				for (int v : postings.get(k)) {
					sb.append(v);
				}
				sb.append(",");
			}
			sb.append("]");
		}
		return sb.toString();
	}
}